<template>
  <div class="wrap">
    <div class="header">
      <div class="left">
        <!-- <el-select
          v-model="queryParams.accountType"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
        >
          <el-option :label="$t('common.allStores')" value=""></el-option>
          <el-option :label="$t('common.Single store')" :value="1"></el-option>
          <el-option :label="$t('common.Multiple Stores')" :value="2"></el-option>
        </el-select> -->

        <!-- <el-select
          v-model="queryParams.platformType"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
          v-if="$store.getters.platformNum > 1"
        >
          <el-option :label="$t('shipment.allPlatforms')" value=""></el-option>
          <el-option
            v-for="item in platformTypeList"
            :key="item.value"
            :label="item.name"
            :value="item.value"></el-option>
        </el-select> -->

        <!-- <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
          v-if="false"
        >
          <el-option :label="$t('picking.All states')" value=""></el-option>
          <el-option :label="$t('user.In cooperation')" :value="1"></el-option>
          <el-option :label="$t('user.Stop cooperation')" :value="2"></el-option>
        </el-select> -->

        <el-input
          size="small"
          style="width: 200px; margin-right: 10px; margin-bottom: 10px"
          v-model="queryParams.keyword"
          :placeholder="$t('common.Search for employee name')"
          @keyup.enter.native="changeOption(true)"
          clearable
          @clear="changeOption(false, 'clear')"
        ></el-input>
        <el-button size="small" type="primary" @click="changeOption(true)">{{ $t('common.search') }}</el-button>
      </div>
      <div class="right">
        <el-button @click="showUserDialog" class="mgl20" type="primary">{{ $t('user.create an employee') }}</el-button>
      </div>
    </div>
    <div class="content">
      <el-table v-loading="loading" :data="data" border ref="tableData">
        <el-table-column prop="account" :label="$t('table.employe name')" align="center" min-width="120" fixed>
          <template slot-scope="{ row }">
            {{ row.account }}
            <!-- <diy-link @click="jumpInfo(row)"></diy-link> -->
          </template>
        </el-table-column>

        <el-table-column prop="status" :label="$t('user.职位')" align="center" min-width="100">
          <template slot-scope="{ row }">
            <template v-if="row.job.length === 0">-</template>
            <template v-else>
              {{ getRolesStr(row.job) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('table.createTime3')" align="center" min-width="150"></el-table-column>
        <el-table-column :label="$t('table.operate')" align="center" width="200">
          <template slot-scope="{ row }">
            <el-button type="primary" @click="editUserDialog(row)">{{ $t('common.edit') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-wrap">
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="userDialog" width="700px">
      <el-form ref="userForm" :model="dialogForm" label-width="130px" :rules="rules">
        <el-form-item :label="$t('table.employe name')" prop="account">
          <el-input v-model.trim="dialogForm.account"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.职位')" prop="job">
          <el-checkbox-group v-model="dialogForm.job">
            <el-checkbox label="salesperson">销售员</el-checkbox>
            <el-checkbox label="customerservice">港前客服</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="userDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button @click="createUser" :loading="userLoading" type="primary">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { generateRandomString, getFalabellaName, getMercadoName, isEmail } from '@/utils';
import request from '@/utils/request';
import { saveEmpolye, getEmpolye } from '@/api/user';
import { getAllAdmin } from '@/api/admin';
import { ROLE_INBOUND_SORTING, ROLE_MIDDLE_TRANSFER, ROLE_ONE_SHIPPING, ROLE_OPERATE } from '@/utils/admin';

export default {
  name: 'employeesList',
  computed: {
    oneShippingAdminList() {
      return this.adminList.filter((item) => {
        return item.roles.indexOf(ROLE_ONE_SHIPPING) !== -1;
      });
    },
    middleTransferAdminList() {
      return this.adminList.filter((item) => {
        return item.roles.indexOf(ROLE_MIDDLE_TRANSFER) !== -1;
      });
    },
    inboundSortingAdminList() {
      return this.adminList.filter((item) => {
        return item.roles.indexOf(ROLE_INBOUND_SORTING) !== -1;
      });
    }
  },
  data() {
    const checkEmail = (rule, value, callback) => {
      request({
        url: '/user/checkEmail',
        method: 'get',
        params: this.dialogForm,
        handleError: true
      }).then((res) => {
        if (res.error !== 0) {
          callback(new Error(res.message));
        } else {
          callback();
        }
      });
    };

    const checkAccount = (rule, value, callback) => {
      request({
        url: '/user/checkAccount',
        method: 'get',
        params: this.dialogForm,
        handleError: true
      }).then((res) => {
        if (res.error !== 0) {
          callback(new Error(res.message));
        } else {
          callback();
        }
      });
    };

    return {
      queryParams: {
        page: 1,
        pageSize: 20,
        accountType: '',
        status: '',
        adminId: '',
        tabType: '',
        platformType: ''
      },
      data: [],
      loading: false,
      userLoading: false,
      total: 0,
      platformTypeList: [],
      userDialog: false,
      is_search: false,
      sortOrders: ['descending', 'ascending', null],
      dialogForm: {
        id: 0,
        job: [],
        account: '',
        password: '',
        email: '',
        oneShippingAdminId: '',
        middleTransferAdminId: '',
        inboundSortingAdminId: ''
      },
      adminList: [],
      title:this.$t('user.create an employee'),
      rules: {
        account: [
          { required: true, message: this.$t('common.pleaseFillIn'), trigger: 'blur' },
          { message: this.$t('user.userValid1'), trigger: 'blur', min: 3 },
          { message: this.$t('user.userValid2'), trigger: 'blur', max: 20 },
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: this.$t('user.userValid3'), trigger: 'blur' }
          // { validator:checkAccount, trigger: 'blur' },
        ],
        password: [
          { required: true, message: this.$t('user.userValid4'), trigger: 'blur', min: 6 },
          { required: true, message: this.$t('user.userValid4'), trigger: 'change', min: 6 },
          { message: this.$t('user.userValid5'), trigger: 'blur', max: 30 }
        ],
        email: [
          // { required: true, message: this.$t('common.pleaseFillIn') ,trigger: 'blur' }, // 校验邮箱格式
          { pattern: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/, message: this.$t('user.userValid6'), trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' } // 校验邮箱格式
        ],
        oneShippingAdminId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }],
        middleTransferAdminId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }],
        job: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }]
      }
    };
    // /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
  },
  created() {
    if (this.$route.name === 'invalidUserList') {
      this.queryParams.tabType = 'invalid';
    } else if (this.$route.name === 'normalUserList') {
      this.queryParams.tabType = 'normal';
    }
    this.getData();
    this.getAdminList();
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    });
  },
  methods: {
    getFalabellaName,
    getMercadoName,
    getData() {
      this.loading = true;
      getEmpolye(this.queryParams).then((res) => {
        this.loading = false;
        this.data = res.data;
        this.total = res.info.total;
        this.platformTypeList = res.info.platformTypeList;
      });
    },
    getRolesStr(roles) {
      const arr = roles.map((item) => {
        // 根据权限获取对应的翻译名称
        return this.getRoleName(item);
      });
      return arr.join('、');
    },
    getRoleName(val) {
      if (val == 'salesperson') {
        return '销售员';
      } else if (val == 'customerservice') {
        return '港前客服';
      }
    },
    // 生成随机密码
    createPassword() {
      this.dialogForm.password = generateRandomString();
    },
    // 创建用户
    createUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.userLoading = true;
          saveEmpolye(this.dialogForm).then((res) => {
            this.userLoading = false;
            if (res.error === 0) {
              this.$successMessage(res.message);
              this.userDialog = false; // 关闭弹窗
              this.resetForm();
              this.getData(); // 重新请求数据
            } else {
              this.$errorMessage(res.message);
            }
          });
        }
      });
    },
    // 重置表单
    resetForm() {
      this.dialogForm.password = '';
      this.dialogForm.account = '';
      this.dialogForm.email = '';
      this.dialogForm.job = [];
      this.dialogForm.id = 0;
    },
    changeOption(is_search = false, type = '') {
      if (is_search == true) {
        //判断是否使用过搜索按钮
        this.is_search = true;
      }
      if (type == 'clear') {
        if (this.is_search == false) {
          return;
        } else {
          this.is_search = false;
        }
      }

      this.queryParams.page = 1;
      this.getData();
    },
    //排序
    handleSortChange(column) {
      this.queryParams.orderBy = '';
      this.queryParams.orderField = '';
      if (column.order) {
        this.queryParams.orderBy = column.order;
        this.queryParams.orderField = column.prop;
      }
      this.queryParams.page = 1;
      this.getData();
    },
    jumpInfo(row) {
      this.$router.push({
        name: 'userInfo',
        query: {
          id: row.id
        }
      });
    },
    // getAdminAccount(admins){
    //   const name = [];
    //   admins.forEach(item=>{
    //     name.push(item.account)
    //   })
    //   return name.join('、')
    // },
    showUserDialog() {
      this.title=this.$t('user.create an employee')
      this.userDialog = true;
      this.dialogForm.account = '';
      this.dialogForm.email = '';
      this.dialogForm.id = 0;
      this.dialogForm.password = '';
      this.dialogForm.oneShippingAdminId = '';
      this.dialogForm.middleTransferAdminId = '';
      this.dialogForm.inboundSortingAdminId = '';
      this.dialogForm.job = [];
      if (this.oneShippingAdminList.length === 1) {
        this.dialogForm.oneShippingAdminId = this.oneShippingAdminList[0].adminId;
      }
      if (this.middleTransferAdminList.length === 1) {
        this.dialogForm.middleTransferAdminId = this.middleTransferAdminList[0].adminId;
      }
      if (this.inboundSortingAdminList.length === 1) {
        this.dialogForm.inboundSortingAdminId = this.inboundSortingAdminList[0].adminId;
      }
    },
    editUserDialog(row) {
      this.title=this.$t('user.update an employee')
      this.userDialog = true;
      this.dialogForm.account = row.account;
      this.dialogForm.job = row.job;
      this.dialogForm.id = row.id;
    }
  }
};
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header {
    display: flex;
    justify-content: space-between;
  }
  .content {
    padding: 20px 0 0;
  }
}
.header-select {
  margin-right: 20px;
}
.form-tips {
  line-height: 20px;
  font-size: 12px;
}
</style>
